<script setup>
import Tabs from "../plugins/tabs.vue";
import TabItem from "../plugins/tab-item.vue";
import Items from "../plugins/items.vue"
import Item from "../plugins/item.vue"
import Panel from "./panel.vue";
import { Pie } from "vue-chartjs";
import { ref, computed, onBeforeMount } from "vue";
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  CategoryScale,
} from "chart.js";
import RecordPanel from "./items/RecordPanel.vue"

ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale);

const result = computed(() => {
  return analysis_result;
});
const filteredStatType = ref(null);
const briefData = computed(() => {
  var labels = []
  var data = []
  if (!staticFiltered.value) {
    labels = Object.keys(result.value.Brief);
    data = Object.values(result.value.Brief);
  } else {
    labels = ["IllegalCount", "LegalCount"]
    data = filtered.value.reduce((prev, res) => {
      if (res.Legal) {
        prev[1]++;
      } else {
        prev[0]++;
      }
      return prev;
    }, [0, 0])
  }
  return {
    labels,
    datasets: [
      {
        backgroundColor: ["#16c566", "#f2481c", "#006eff", "#DD1B16"],
        data,
      },
    ],
  };
});
const statPie = ref(null);
const filtered = ref([]);
const shownDetail = computed(() => {
  if (staticFiltered.value) {
    filtered.value = result.value.Detail.filter((item) => {
      var stype = fitleredFileType.find((typ) => item.Url.endsWith(typ));
      return !stype;
    });
  } else {
    filtered.value = result.value.Detail;
  }
  var filteredOfThisType;
  if (filteredStatType.value) {
    filteredOfThisType = filtered.value.filter(
      (item) =>
        !filteredStatType.value ||
        (filteredStatType.value == "LegalCount" && item.Legal) ||
        (filteredStatType.value == "IllegalCount" && !item.Legal)
    );
  } else {
    filteredOfThisType = filtered.value;
  }

  return filteredOfThisType;
});
const static_filtered_cache = ref(null);
const staticFiltered = computed({
  get() {
    if (static_filtered_cache.value == null) {
      var json = localStorage.getItem("static_filtered");
      static_filtered_cache.value = JSON.parse(json);
    }
    return static_filtered_cache.value;
  },
  set(to) {
    static_filtered_cache.value = to;
    var json = JSON.stringify(to);
    localStorage.setItem("static_filtered", json);
  },
});
const fitleredFileType = [".js", ".png", ".jpg", ".jpeg", ".js", ".css", ".html", "svg"];

const currentTab = ref('brief');
const selectedClient = ref(null);
const shownDetailForClient = computed(() => {
  return shownDetail.value.filter(item =>
    item.Client == selectedClient.value
  )
})

onBeforeMount(() => {
  window.onpopstate = (event) => {
    console.log(event)
    var tab = event.path?.[0]?.location?.hash.replace("#", '')
    if (!tab) {
      tab = "brief"
    }
    console.log(tab)
    currentTab.value = tab
    if (event.state && event.client) {
      selectedClient.value = event.client;
    }
  };
})

function handleClick(e) {
  const points = statPie.value.chart.getElementsAtEventForMode(
    e,
    "nearest",
    { intersect: true },
    true
  );

  if (points.length) {
    const firstPoint = points[0];
    const label = statPie.value.chart.data.labels[firstPoint.index];
    const value =
      statPie.value.chart.data.datasets[firstPoint.datasetIndex].data[
      firstPoint.index
      ];
    if (filteredStatType.value == label) {
      filteredStatType.value = null;
    } else {
      filteredStatType.value = label;
    }
  }
}

function setStaticFilter() {
  staticFiltered.value = !staticFiltered.value;
}



function gotoClientPage(client) {
  history.pushState({
    client
  }, '', '#clients');
  currentTab.value = "clients";
  selectedClient.value = client;
}

function gotoPage(val) {
  history.pushState({}, '', '#' + val);
  currentTab.value = val;
}

</script>

<template>
  <tabs v-model="currentTab" @input="gotoPage">
    <tab-item label="统计简报" name="brief">
      <panel label="访问统计">
        <Pie :chart-data="briefData" :chart-options="{
          onClick: handleClick,
        }" width="90%" height="90%" class="pie-chart" ref="statPie" />
        <items :label-width="120">
          <item label="数据总条数：">
            {{ result.Detail.length }}条
          </item>
          <item label="过滤后总条数：">{{ filtered.length }}条</item>
          <item label="记录客户数">{{ result.ClientCount }}个</item>
        </items>
      </panel>
      <record-panel style="flex:1" :records="shownDetail" @select-client="gotoClientPage"></record-panel>
    </tab-item>
    <tab-item label="客户报告" name="clients">
      <panel label="客户端列表" style="max-width:200px">
        <ul class="clients">
          <li v-for="(v, k) in result.Clients" :key="k" :class="{ active: k == selectedClient }"
            @click="selectedClient = k">
            {{ k }}</li>
        </ul>
      </panel>
      <record-panel style="flex:1" :records="shownDetailForClient"></record-panel>
    </tab-item>
    <tab-item label="不合法访问"></tab-item>
  </tabs>
</template>

<style lang="scss" scoped>
.pie-chart {
  height: 70%;
  width: 70%;
  margin: auto;
  margin-top: 1em;
}

.clients {
  list-style: none;
  padding-inline-start: 0;

  li {
    padding: 5px 10px;

    &:nth-child(2n+1) {
      background-color: #f4f4f4;
    }

    &.active {
      color: #666666;
      background-color: var(--logcat-info-color-light);
    }
  }
}
</style>